package shuashuami.hb.com.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import shuashuami.hb.com.adapter.TaskAdatper;
import shuashuami.hb.com.avtivity.ComplaintActivity;
import shuashuami.hb.com.avtivity.NoticeActivity;
import shuashuami.hb.com.avtivity.VIPTaskActivity;
import shuashuami.hb.com.hbclient.R;
import shuashuami.hb.com.hdlibrary.glid.GlidUtil;
import shuashuami.hb.com.hdlibrary.util.ToastUtil;
import shuashuami.hb.com.http.HttpCMethods;
import shuashuami.hb.com.http.HttpOnNextListener;
import shuashuami.hb.com.http.LoginHttp;
import shuashuami.hb.com.model.Task;
import shuashuami.hb.com.view.OnlineConsultingDialog;
import shuashuami.hb.com.view.OverScrollView;

/**
 * <b>类   名：</b>${TYPE_NAME} <br/>
 * <b>类描述：</b> <br/>
 * <b>创建人：</b>zhangqi<br/>
 * <b>创建时间：</b>2017/6/13<br/>
 * <b>修改人：</b>zhangqi<br/>
 * <b>修改时间：</b>2017/6/13<br/>
 * <b>修改备注：</b><br/>
 *
 * @version 1.0.0<br/>
 */
public class HbCHomeFragm extends AbFragment implements OverScrollView.OverScrollListener, OverScrollView.OverScrollTinyListener {

    private LinearLayout llOnlineConsulting;
    private LinearLayout llToNotice;
    private LinearLayout llToComplaint;
    private TextView tvToVipTask;

    private ImageView imgBanner;
    private TextView tvNotice;
    private ListView lvTask;

    private GlidUtil glidUtil;

    private String qq, phone;

    @Override
    public void initView(View v) {
        setTitleBar("首页");
        llOnlineConsulting = (LinearLayout) v.findViewById(R.id.ll_chome_oline_consulting);
        llToNotice = (LinearLayout) v.findViewById(R.id.ll_chome_to_notice);
        llToComplaint = (LinearLayout) v.findViewById(R.id.ll_chome_to_complaint);
        tvToVipTask = (TextView) v.findViewById(R.id.tv_chome_all_vip_task);
        imgBanner = (ImageView) v.findViewById(R.id.img_chome_banner);
        tvNotice = (TextView) v.findViewById(R.id.tv_chome_notice);
        lvTask = (ListView) v.findViewById(R.id.lv_home_hall_items);
    }

    @Override
    public void initData() {
        list = new ArrayList<>();
        glidUtil = new GlidUtil(getActivity());

        OverScrollView scrollView = (OverScrollView) findViewById(R.id.layout);

        scrollView.setOverScrollListener(this);
        scrollView.setOverScrollTinyListener(this);

        // 隐藏图片的初始边界
        // 保证下拉能出现放大图片的效果
        scrollLoosen();
    }

    @Override
    public void initListener() {
        llOnlineConsulting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showOnlineConsultingDialog();
            }
        });

        llToNotice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), NoticeActivity.class);
                if (position == 0) {
                    intent.putExtra("id", listNoticeId.get(0));
                } else {
                    intent.putExtra("id", listNoticeId.get(position - 1));
                }

                startActivity(intent);
            }
        });

        llToComplaint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ComplaintActivity.class);
                startActivity(intent);
            }
        });
        tvToVipTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), VIPTaskActivity.class);
                startActivity(intent);
            }
        });
    }

    private void showOnlineConsultingDialog() {
        OnlineConsultingDialog onlineConsultingDialog = new OnlineConsultingDialog(getActivity(), qq, phone);
        onlineConsultingDialog.show();
    }

    @Override
    public int bindView() {
        return R.layout.frag_chome;
    }

    private ProgressDialog progressDialog;

    //主界面获取
    private void getHomePage() {
        progressDialog = ProgressDialog.show(getActivity(), "加载中...", "请稍后...", true, false);
        HttpOnNextListener<String> listener = new HttpOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                Message message = handler.obtainMessage(1);     // Message
                message.obj = s;
                handler.sendMessageDelayed(message, 0);
            }
        };
        HttpCMethods.getHomePage(listener);
    }

    private boolean isFirst = true;

    List<String> listNotice = new ArrayList<>();
    List<String> listNoticeId = new ArrayList<>();
    private int position = 0;
    private int TIME = 2000;
    Handler handler2;
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            // handler自带方法实现定时器
            try {
                handler2.postDelayed(this, TIME);
                if (position < listNotice.size()) {
                    tvNotice.setText(listNotice.get(position));
                    position += 1;
                } else {
                    position = 0;
                    tvNotice.setText(listNotice.get(position));
                    position += 1;
                }

                System.out.println("do...");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("exception...");
            }
        }
    };

    private List<Task> list;
    final Handler handler = new Handler() {

        public void handleMessage(Message msg) {         // handle message
            switch (msg.what) {
                case 1:
                    progressDialog.dismiss();
                    try {
                        list.clear();
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        if (jsonObject.getInt("status") == 203) {
                            LoginHttp loginHttp = new LoginHttp(getActivity());
                            loginHttp.login();
                            return;
                        }
                        if (jsonObject.getInt("status") == 200) {
                            JSONObject content = jsonObject.getJSONObject("content");
                            JSONArray jsonBannerList = content.getJSONArray("banner_list");
                            if (jsonBannerList.length() > 0) {
                                JSONObject temp = jsonBannerList.getJSONObject(0);
                                glidUtil.uploadImage(temp.getString("image"), R.mipmap.ic_launcher, imgBanner);
                            }
                            JSONArray notice_list = content.getJSONArray("notice_list");
                            for (int i = 0; i < notice_list.length(); i++) {
                                JSONObject temp = notice_list.getJSONObject(i);
                                listNotice.add(temp.getString("title"));
                                listNoticeId.add(temp.getString("aid"));
                            }
                            if (notice_list.length() > 0) {
                                JSONObject temp = notice_list.getJSONObject(0);
                                tvNotice.setText(temp.getString("title"));
                                if (isFirst) {
                                    isFirst = false;
                                    handler2 = new Handler();
                                    handler2.postDelayed(runnable, TIME); //每隔1s执行
                                }
                            }
                            JSONArray task_list = content.getJSONArray("task_list");
                            for (int i = 0; i < task_list.length() && i < 2; i++) {
                                JSONObject temp = task_list.getJSONObject(i);
                                Task task;
                                if (temp.getInt("need_comment") == 2) {
                                    task = new Task(temp.getString("id"),
                                            temp.getString("platform_image"), temp.getString("addtime"), "需要", temp.getString("spot_money"), temp.getString("commission"),
                                            temp.getString("task_sn"), temp.getInt("num"),
                                            temp.getString("type_name"), temp.getString("goods_type_name"), false, temp.getString("vip_commission"));
                                } else {
                                    task = new Task(temp.getString("id"),
                                            temp.getString("platform_image"), temp.getString("addtime"), "不需要", temp.getString("spot_money"),
                                            temp.getString("commission"), temp.getString("task_sn"), temp.getInt("num"),
                                            temp.getString("type_name"), temp.getString("goods_type_name"), false, temp.getString("vip_commission"));
                                }
                                list.add(task);
                            }
                            if (list.size() > 0) {
                                adatper();
                            }
                            qq = content.getString("qq");
                            phone = content.getString("telephone");
                        } else {
                            ToastUtil.showShort(getActivity(), jsonObject.getString("message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

            }
            super.handleMessage(msg);
        }
    };
    private TaskAdatper adatper;

    private void adatper() {
        adatper = new TaskAdatper(list, getActivity());
        lvTask.setAdapter(adatper);
    }

    @Override
    public void onResume() {
        super.onResume();
        getHomePage();
    }
    /**
     * 初始化填充值，控制图片被隐藏的边缘值
     */
    private static final int PADDING = -100;
    @Override
    public void scrollDistance(int tinyDistance, int totalDistance) {
        int padding = PADDING - totalDistance / 2;
        if (padding > 0) {
            padding = 0;
        }
    }

    @Override
    public void scrollLoosen() {
     //   getHomePage();
        // 滑动处理松开时回调
    }

    @Override
    public void headerScroll() {
      //  Toast.makeText(getActivity(), "开始刷新", Toast.LENGTH_SHORT).show();
        getHomePage();
        // 处理下拉超过一定临界值时 的回调
    }

    @Override
    public void footerScroll() {
        // 处理上拉超过一定临界值时 的回调
    }


}
